var express = require('express');
var router = express.Router();
var {formidable} = require('formidable');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get('/upload', function(req, res, next) {
  res.render('upload');
});

// 处理文件上传
router.post('/upload',function(req,res,next){
// 创建 form 对象
  const form = formidable({
    multiples: true,
    // 设置上传文件的保存目录
    uploadDir: __dirname + '/../public/images',
    // 保留文件后缀
    keepExtensions: true
  });
// 解析请求报文
  form.parse(req, (err, fields, files) => {
    console.log(fields,files)
    // { title: [ 'asd ' ], author: [ '123' ] }   fields
    // {
    //   file: [
    //     PersistentFile {
    //       _events: [Object: null prototype],
    //       _eventsCount: 1,
    //       _maxListeners: undefined,
    //       lastModifiedDate: 2024-08-16T01:58:46.515Z,
    //       filepath: 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\85f2ba4de3340553c2251d400',
    //       newFilename: '85f2ba4de3340553c2251d400',
    //       originalFilename: 'Snipaste_2024-08-15_11-19-04.png',
    //       mimetype: 'image/png',
    //       hashAlgorithm: false,
    //       size: 5809,
    //       _writeStream: [WriteStream],
    //       hash: null,
    //       [Symbol(kCapture)]: false
    //     }
    //   ]
    // }

    // 服务器保存该图片的url
    let url = '/images/' + files.file[0].newFilename; //将来将此数据保存到数据库中
    res.send(url);
  });
 
})

module.exports = router;
